import { Address } from '@/apis/order/sameCityOrder/types'

export default function computedDistance(loc1: Address['location']['coordinates'], loc2: Address['location']['coordinates']) {
    if (!Array.isArray(loc1) || !Array.isArray(loc2)) {
        return 0
    }
    if (!loc1.length || !loc2.length) {
        return 0
    }
    const lat1Rad = loc1[1] * (Math.PI / 180)
    const lon1Rad = loc1[0] * (Math.PI / 180)
    const lat2Rad = loc2[1] * (Math.PI / 180)
    const lon2Rad = loc2[0] * (Math.PI / 180)
    const dLat = lat2Rad - lat1Rad
    const dLon = lon2Rad - lon1Rad
    const R = 6371 // 地球半径，单位：千米
    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(dLon / 2) * Math.sin(dLon / 2)
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
    // 保留两位小数
    const distance = Math.round(R * c * 100) / 100
    return distance
}
